package cn.gov.customs.h2018;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class ParallelRequestApplication {

  public static void main(String[] args) {
    SpringApplication.run(ParallelRequestApplication.class, args);
  }

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    // return builder.build();
    return new RestTemplate(getClientHttpRequestFactory());
  }

  private ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
    int timeout = 5000;
    RequestConfig config =
        RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build();
    CloseableHttpClient client =
        HttpClientBuilder.create()
            .setConnectionManager(poolingConnManager)
            .setDefaultRequestConfig(config)
            .build();
    return new HttpComponentsClientHttpRequestFactory(client);
  }
}
